package demo0109_jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.util.Scanner;

/**
 * Created by ztt on 2017/9/13.
 */
public class JdbcMain {@SuppressWarnings("resource")
    public static void main(String[] args) {
        //加载xml配置文件
        //ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:demo0109_jdbc/jdbc.xml");
        ApplicationContext ctx = new FileSystemXmlApplicationContext("E:\\workspace-intellij\\Spring4\\src\\main\\resources\\demo0109_jdbc\\jdbc.xml");
        //取得Bean类并且映射为DAO类
        JdbcUtil dao = ctx.getBean(JdbcUtil.class);
        add(dao);
    }

    public static void createTable(JdbcUtil dao){
        Article article=new Article();
        article.setContent("content"+Math.random());
        article.setTitle("title"+Math.random());
        dao.createTable("article",article);
    }

    public static void add(JdbcUtil dao){
        Article article=new Article();
        article.setContent("content"+Math.random());
        article.setTitle("title"+Math.random());
        dao.add(article);
    }

    public static void find(JdbcUtil dao){
        int id = 0;
        Scanner s = new Scanner(System.in);
        while (true) {
            System.out.println("输入查询id：");
            id = s.nextInt();
            try {
                Article a = dao.find(id); // 传入id查询
                System.out.println(a);
            } catch (Exception e) {
                //抛出查不到的异常，不要让查询错误使得程序结束
                System.out.println("查询不到结果！");// 传入id找不到就报错
            }
            System.out.println();
        }
    }
}
